<template>
  <div class="login-log-list">
    <de-container v-loading="$store.getters.loadingMap[$store.getters.currentPath]" class="pa-5">
      <avue-crud
        ref="crud"
        v-model="form"
        :data="tableData"
        :table-loading="tableLoading"
        :option="tableOption"
        :search.sync="searchForm"
        @on-load="loadListData"
        @search-change="onSearchChange"
        @search-reset="onCustomSearchReset"
        @refresh-change="onRefresh"
        @selection-change="onSelectionChange"
        @filter-change="onFilterChange"
        @sort-change="onSortChange"
      >
        <template slot="menuLeft">
          <el-button type="primary" icon="el-icon-plus" size="small" @click="onAdd()">新建</el-button>
        </template>
        <template slot="menu" slot-scope="{ row }">
          <el-button type="text" size="small" @click="goDetail(row)">详情</el-button>
          <el-button type="text" size="small" :disabled="row.distributionStatus === '1'" @click="goEdit(row)"
            >编辑</el-button
          >
          <el-button type="text" size="small" @click="onAdd(row)">添加</el-button>
          <el-dropdown trigger="click">
            <el-button type="text" size="small" style="margin-left: 8px">
              <i class="el-icon-more" style="transform: rotate(90deg); font-size: 16px"></i>
            </el-button>
            <el-dropdown-menu slot="dropdown">
              <el-dropdown-item v-if="targetType === '0'">
                <el-button type="text" size="small" @click="distributionStatusChange(row)">{{
                  row.distributionStatus === '0' ? '目标下发' : '下发撤回'
                }}</el-button>
              </el-dropdown-item>
              <el-dropdown-item v-if="targetType === '0'">
                <el-button type="text" size="small" @click="goAuth(row)">权限设置</el-button>
              </el-dropdown-item>
              <el-dropdown-item>
                <el-button type="text" size="small" @click="onRowDelete(row)">删除</el-button>
              </el-dropdown-item>
            </el-dropdown-menu>
          </el-dropdown>
        </template>
        <template slot="period" slot-scope="{ row }">
          <span v-if="row.beginTargetPeriod && row.endTargetPeriod"
            >{{ moment(row.beginTargetPeriod).format('YYYY-MM-DD') }} -
            {{ moment(row.endTargetPeriod).format('YYYY-MM-DD') }}</span
          >
        </template>
        <template slot="targetStatus" slot-scope="{ row }">
          <span>
            {{ row.ruleType === '0' ? '无状态' : row.targetStatus }}
          </span>
        </template>
        <template slot="ratio" slot-scope="{ row }">
          {{ (((row.currentValue - row.initValue) / (row.targetValue - row.initValue)) * 100).toFixed(2) + '%' }}
          <el-progress
            stroke-width="3"
            :show-text="false"
            width="20"
            type="circle"
            :percentage="(((row.currentValue - row.initValue) / (row.targetValue - row.initValue)) * 100).toFixed(2)"
          ></el-progress>
        </template>
        <template slot="periodSearch">
          <el-date-picker
            v-model="searchForm.period"
            type="daterange"
            align="right"
            unlink-panels
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            :picker-options="pickerOptions()"
          >
          </el-date-picker>
        </template>
        <template slot="targetStatus" slot-scope="{ row }">
          <el-dropdown trigger="click" :disabled="row.ruleType !== '1'">
            <span :style="statusMap[row.targetStatus || '无状态']" class="status-tag"
              >{{ row.targetStatus || '无状态' }}
              <i v-if="row.ruleType === '1'" class="el-icon-arrow-down" style="margin-left: 8px"></i>
            </span>
            <el-dropdown-menu>
              <el-dropdown-item
                v-for="item in ['正常', '有风险', '未完成', '完成', '无状态']"
                :key="item"
                @click.native="changeStatus(item, row)"
              >
                <span :style="statusMap[item]" class="status-tag">{{ item }} </span>
              </el-dropdown-item>
            </el-dropdown-menu>
          </el-dropdown>
        </template>
      </avue-crud>
      <el-drawer
        title="指标目标"
        :visible.sync="open"
        size="60%"
        destroy-on-close
        :append-to-body="false"
        :modal-append-to-body="false"
        @closed="showForm = false"
      >
        <MyAimEdit
          :id="currentId"
          :parent-id="parentId"
          :is-detail="isDetail"
          @close="open = false"
          @refresh="onCustomSearchReset"
        ></MyAimEdit>
      </el-drawer>
    </de-container>
  </div>
</template>
<script>
import { list, del, update, targetDistribute, targetWithdraw, getDBLastData } from '@/api/target/target'
import DeContainer from '@/components/dataease/DeContainer'
import ListMixin from '@/utils/mixins/list-mixin'
import moment from 'moment'
import { ApplicationContext } from '@/utils/ApplicationContext'
import { status } from '@/utils/color'
import MyAimEdit from './my-aim-edit.vue'
import { parse } from '@/utils/valueFormatter'
const DEFAULT_LIST_MAP_FUNC = (item) => {
  const ret = item

  return ret
}
const DEFAULT_EDIT_MAP_FUNC = (item) => {
  const ret = item
  item.switching = false

  return ret
}

export default {
  name: 'Chart',
  components: { DeContainer, MyAimEdit },
  mixins: [ListMixin],
  props: {
    keyIndex: {
      type: String,
      default: '',
    },
  },
  data() {
    return {
      statusMap: status,
      moment,
      listApi: this.list,
      deleteApi: del,
      listMapFunc: DEFAULT_LIST_MAP_FUNC,
      editMapFunc: DEFAULT_EDIT_MAP_FUNC,
      tableOption: {
        menuWidth: 220,
        addBtn: false,
        editBtn: false,
        viewBtn: false,
        delBtn: false,
        selection: false,
        menuFixed: 'right',
        index: true,
        searchLabelWidth: 100,
        searchMenuPosition: 'left',
        column: [
          {
            label: '目标名称',
            prop: 'name',
            search: true,
            span: 12,
            align: 'left',
            overHidden: true,
            formatter: (row) => {
              if (row.loaded) {
                return row.name
              }
              let matrixItem = this.listObj.find((item) => item.matrixId === row.matrixId)
              if (matrixItem) {
                row.loaded = true
                let panelId = matrixItem.sceneId
                getDBLastData({ panelId }).then((res) => {
                  row.currentValue = res.data?.data?.value || ''
                })
              }
              return row.name
            },
          },
          {
            label: '指标名称',
            search: true,
            prop: 'matrixId',
            align: 'left',
            // hide: true,
            type: 'select',
            span: 12,
            rules: [{ required: true, message: '请选择指标' }],
            dicUrl: '/jtx/index/chartList',
            // props: {
            //   label: 'name',
            //   value: 'name',
            // },
            overHidden: true,
            dicMethod: 'post',
            filterable: true,
            dicFormatter: (res) => {
              this.listObj = res.map((item) => ({ ...item }))
              this.tableData = JSON.parse(JSON.stringify(this.tableData))
              return res
            },
            props: {
              label: 'name',
              value: 'matrixId',
            },
            dicQuery: {
              publishStatus: '1',
            },
          },
          {
            label: '日期范围',
            prop: 'period',
            span: 12,
            align: 'left',
            search: true,
            // overHidden: true,
            type: '',
            width: 200,
          },
          {
            label: '下发状态',
            prop: 'distributionStatus',
            span: 12,
            align: 'left',
            // search: true,
            overHidden: true,
            dicData: [
              { label: '未下发', value: '0' },
              { label: '已下发', value: '1' },
            ],
            type: '',
          },
          {
            label: '当前值',
            prop: 'currentValue',
            span: 12,
            align: 'left',
            overHidden: true,
            formatter: (row) => {
              row.targetStatus = this.setStatus(row)
              return parse(row.currentValue, row.valueFormat)
            },
          },
          {
            label: '目标值',
            prop: 'targetValue',
            span: 12,
            align: 'left',
            overHidden: true,
            formatter: (row) => {
              return parse(row.targetValue, row.valueFormat)
            },
          },
          {
            label: '进度',
            prop: 'ratio',
            span: 12,
            align: 'left',
            overHidden: true,
            formatter: (row) => {
              return (((row.currentValue - row.initValue) / (row.targetValue - row.initValue)) * 100).toFixed(2) + '%'
            },
          },
          {
            label: '目标状态',
            prop: 'targetStatus',
            width: 120,
            span: 12,
          },
          {
            label: '责任部门',
            prop: 'responsibleDeptId',
            type: 'tree',
            props: {
              label: 'name',
              value: 'deptId',
            },
            dicUrl: '/api/dept/tree',
            dicMethod: 'post',
            dicQuery: {},
            search: true,
            rules: [{ required: true, message: '请选择责任部门' }],
            addDisabled: false,
            span: 12,
            align: 'left',
            overHidden: true,
          },
          {
            label: '责任人',
            prop: 'responsibleUserId',
            type: 'select',
            span: 12,
            rules: [{ required: true, message: '请选择责任人' }],
            dicUrl: '/api/user/userGrid/1/999',
            props: {
              label: 'nickName',
              value: 'userId',
            },
            dicMethod: 'post',
            dicFormatter: (res) => res.listObject,
            overHidden: true,
          },
        ],
      },
      open: false,
      showForm: false,
      parentId: '',
      currentId: '',
      isDetail: false,
      listObj: [],
    }
  },
  computed: {
    targetType() {
      if (this.keyIndex) {
        return this.keyIndex === '1-1' ? '0' : '1'
      }
      return this.$route.path === '/aim/group-aim-list' ? '0' : '1'
    },
  },
  methods: {
    async list(params) {
      delete params.pageNo
      delete params.pageSize
      if (params.period && params.period.length) {
        params.beginTargetPeriod = moment(params.period[0]).format('YYYY-MM-DD HH:mm:ss')
        params.endTargetPeriod = moment(params.period[1]).format('YYYY-MM-DD HH:mm:ss')
      }
      params.targetType = this.targetType
      let res = await list(params)
      let data = JSON.parse(JSON.stringify(res.data))
      if (!data) return { ...res, data: { listObject: [] } }

      res.data = {}
      res.data.listObject = data
      return res
    },

    setStatus(row) {
      if (row.targetStatus) return row.targetStatus
      if (row.ruleJson) {
        let ruleJson = JSON.parse(row.ruleJson)
        for (let val of ruleJson) {
          if (
            (val.condition === '大于等于' && val.leftValue / 1 <= row.currentValue / 1) ||
            (val.condition === '两值之间' &&
              row.currentValue / 1 >= val.leftValue &&
              row.currentValue / 1 <= val.rightValue) ||
            (val.condition === '小于等于' && row.currentValue / 1 <= val.rightValue / 1)
          ) {
            return val.status
          }
        }
      }
      return ''
    },

    // async getTargetValue(data){
    //   for(let val of data){
    //     if(val.children){
    //       await this.getTargetValue(val.children)
    //       if(val.currentValueType==='0'){
    //         let res = await getDBLastData()
    //       }
    //     }
    //   }

    // },

    goDetail(row) {
      // this.$router.push(`/redirect/aim/${row.id}/my-aim-detail`)
      this.currentId = row.id
      this.parentId = row.parentId === '0' ? '' : row.parentId || 0
      this.isDetail = true

      this.open = true
      this.showForm = true
    },
    goEdit(row) {
      // this.$router.push(`/redirect/aim/${row.id}/my-aim-edit`)
      this.isDetail = false
      this.currentId = row.id
      this.parentId = row.parentId === '0' ? '' : row.parentId || 0

      this.open = true
      this.showForm = true
    },
    onCustomSearchReset() {
      this.onSearchReset()
    },
    onAdd(row) {
      // if (typeof parentId !== 'string') this.$router.push('/redirect/aim/my-aim-add')
      // else this.$router.push({ path: '/redirect/aim/my-aim-add', query: { parentId } })
      this.parentId = row?.id || ''
      this.isDetail = false
      this.currentId = ''

      this.open = true
      this.showForm = true
    },
    pickerOptions() {
      const widget = ApplicationContext.getService('timeDateRangeWidget')
      if (widget.shortcuts) {
        const cuts = widget.shortcuts()
        const result = cuts.map((cut) => {
          return {
            text: this.$t(cut.text),
            onClick: (picker) => {
              const param = cut.callBack()
              picker.$emit('pick', param)
            },
          }
        })
        return {
          shortcuts: result,
        }
      }
      return null
    },
    parse,
    changeStatus(targetStatus, row) {
      if (targetStatus === '无状态') targetStatus = ''
      row.targetStatus = targetStatus
      update({
        id: row.id,
        targetStatus,
      }).then((res) => {
        if (res.success) {
          this.$message.success('状态修改成功')
          this.onSearchReset()
        }
      })
    },
    async distributionStatusChange(row) {
      if (row.children?.length && row.distributionStatus === '0') {
        this.$confirm('下发子目标', {
          confirmButtonText: '下发子目标',
          cancelButtonText: '稍后下发',
          type: 'warning',
        })
          .then(async () => {
            let res = await targetDistribute({ id: row.id, subFlag: true })
            if (res.success) {
              this.$message.success('下发成功')
              this.onSearchReset()
            }
          })
          .catch(async () => {
            let res = await targetDistribute({ id: row.id, subFlag: false })
            if (res.success) {
              this.$message.success('下发成功')
              this.onSearchReset()
            }
          })
      } else if (row.distributionStatus === '0') {
        let res = await targetDistribute({ id: row.id, subFlag: false })
        if (res.success) {
          this.$message.success('下发成功')
          this.onSearchReset()
        }
      } else {
        let res = await targetWithdraw({ id: row.id })
        if (res.success) {
          this.$message.success('撤回成功')
          this.onSearchReset()
        }
      }
    },
    goAuth(row) {
      if (this.$route.path === '/home/target-task') {
        this.$router.push(`/redirect/home/target-task/${row.id}/aim-auth`)
      } else {
        this.$router.push(`/redirect/aim/${row.id}/aim-auth`)
      }
    },
  },
}
</script>

<style lang="scss" scoped>
// ::v-deep {
//   .el-drawer__header {
//     padding-top: 10px;
//     margin-bottom: 10px;
//   }

//   .el-drawer .avue-form {
//     padding-top: 0;
//   }
//   .el-drawer .el-drawer__body {
//     border-top: 1px solid #eee;
//   }
// }

.status-tag {
  width: 83px;
  height: 24px;
  line-height: 22px;
  border-radius: 12px;
  display: inline-block;
  text-align: center;
}

::v-deep .avue-crud .avue-crud__menu i {
  display: block;
}
</style>
